package com.clouddisk.file.strategy.impl;

import com.clouddisk.common.util.MinioUtil;
import com.clouddisk.file.strategy.FileHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
@RequiredArgsConstructor
public class ImageFileHandler implements FileHandler {

    private final MinioUtil minioUtil;

    private static final List<String> SUPPORTED_TYPES = Arrays.asList(
            "image/jpeg", "image/png", "image/gif"
    );

    @Override
    public String getFileType() {
        return "image";
    }

    @Override
    public String handleUpload(MultipartFile file) {
        // 上传原图
        String storagePath = minioUtil.uploadFile(file);
        
        // TODO: 生成缩略图
        
        return storagePath;
    }

    @Override
    public byte[] handlePreview(String storagePath) {
        // 获取缩略图，如果没有则返回原图
        return minioUtil.downloadFile(storagePath);
    }

    @Override
    public boolean isValid(MultipartFile file) {
        if (!SUPPORTED_TYPES.contains(file.getContentType())) {
            return false;
        }

        try {
            // 验证是否为有效的图片文件
            return ImageIO.read(new ByteArrayInputStream(file.getBytes())) != null;
        } catch (IOException e) {
            return false;
        }
    }
} 